<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- 
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License. 
-->
<html>
<head>
    <link type="text/css" rel="stylesheet" href="https://struts.apache.org/css/default.css">
    <style type="text/css">
        .dp-highlighter {
            width:95% !important;
        }
    </style>
    <style type="text/css">
        .footer {
            background-image:      url('https://cwiki.apache.org/confluence/images/border/border_bottom.gif');
            background-repeat:     repeat-x;
            background-position:   left top;
            padding-top:           4px;
            color:                 #666;
        }
    </style>
    <link href='https://struts.apache.org/highlighter/style/shCoreStruts.css' rel='stylesheet' type='text/css' />
    <link href='https://struts.apache.org/highlighter/style/shThemeStruts.css' rel='stylesheet' type='text/css' />
    <script src='https://struts.apache.org/highlighter/js/shCore.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushPlain.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushXml.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushJava.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushJScript.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushGroovy.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushBash.js' type='text/javascript'></script>
    <script type="text/javascript">
        SyntaxHighlighter.defaults['toolbar'] = false;
        SyntaxHighlighter.all();
    </script>
    <script type="text/javascript" language="javascript">
        var hide = null;
        var show = null;
        var children = null;

        function init() {
            /* Search form initialization */
            var form = document.forms['search'];
            if (form != null) {
                form.elements['domains'].value = location.hostname;
                form.elements['sitesearch'].value = location.hostname;
            }

            /* Children initialization */
            hide = document.getElementById('hide');
            show = document.getElementById('show');
            children = document.all != null ?
                    document.all['children'] :
                    document.getElementById('children');
            if (children != null) {
                children.style.display = 'none';
                show.style.display = 'inline';
                hide.style.display = 'none';
            }
        }

        function showChildren() {
            children.style.display = 'block';
            show.style.display = 'none';
            hide.style.display = 'inline';
        }

        function hideChildren() {
            children.style.display = 'none';
            show.style.display = 'inline';
            hide.style.display = 'none';
        }
    </script>
    <title>AJAX</title>
</head>
<body onload="init()">
<table border="0" cellpadding="2" cellspacing="0" width="100%">
    <tr class="topBar">
        <td align="left" valign="middle" class="topBarDiv" align="left" nowrap>
            &nbsp;<a href="home.html">Home</a>&nbsp;&gt;&nbsp;<a href="guides.html">Guides</a>&nbsp;&gt;&nbsp;<a href="core-developers-guide.html">Core Developers Guide</a>&nbsp;&gt;&nbsp;<a href="ajax.html">AJAX</a>
        </td>
        <td align="right" valign="middle" nowrap>
            <form name="search" action="https://www.google.com/search" method="get">
                <input type="hidden" name="ie" value="UTF-8" />
                <input type="hidden" name="oe" value="UTF-8" />
                <input type="hidden" name="domains" value="" />
                <input type="hidden" name="sitesearch" value="" />
                <input type="text" name="q" maxlength="255" value="" />
                <input type="submit" name="btnG" value="Google Search" />
            </form>
        </td>
    </tr>
</table>

<div id="PageContent">
    <div class="pageheader" style="padding: 6px 0px 0px 0px;">
        <!-- We'll enable this once we figure out how to access (and save) the logo resource -->
        <!--img src="/wiki/images/confluence_logo.gif" style="float: left; margin: 4px 4px 4px 10px;" border="0"-->
        <div style="margin: 0px 10px 0px 10px" class="smalltext">Apache Struts 2 Documentation</div>
        <div style="margin: 0px 10px 8px 10px"  class="pagetitle">AJAX</div>

        <div class="greynavbar" align="right" style="padding: 2px 10px; margin: 0px;">
            <a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=34512">
                <img src="https://cwiki.apache.org/confluence/images/icons/notep_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Edit Page"></a>
            <a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=34512">Edit Page</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">
                <img src="https://cwiki.apache.org/confluence/images/icons/browse_space.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Browse Space"></a>
            <a href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">Browse Space</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=34512">
                <img src="https://cwiki.apache.org/confluence/images/icons/add_page_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Add Page"></a>
            <a href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=34512">Add Page</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=34512">
                <img src="https://cwiki.apache.org/confluence/images/icons/add_blogentry_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Add News"></a>
            <a href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=34512">Add News</a>
        </div>
    </div>

    <div class="pagecontent">
        <div class="wiki-content">
            <div id="ConfluenceContent"><p>AJAX is an acronym for Asynchronous JavaScript and XML. Essentially, a JavaScript can make a HTTP request and update portions of a page directly, without going through a conventional POST or GET and refreshing the entire page. Better yet, a page can contain several JavaScripts making simultaneous (asynchronous) requests.</p><p>The key point is that when a script makes an "Ajax request" (XHR), the server doesn't know it came from a script, and handles it like any other request. One reason Ajax is so successful is that it works just fine with existing server technologies, including Struts.</p><p>It's not the Ajax request that is different, but the Ajax response. Instead of returning an entire page for the browser to display (or redisplay), an Ajax response will just return a portion of a page. The response can take the form of XML, or HTML, or plain text, another script, or whatever else the calling script may want.</p><p>Both Struts 1 and Struts 2 can return any type of response. We are not limited to forwarding to a server page. In Struts 1, you can just do something like:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Hello World!  This is an AJAX response from a Struts Action.");
out.flush();
return null;
</pre>
</div></div><p>In Struts 2, we can do the same thing with a Stream result.</p><div class="confluence-information-macro confluence-information-macro-note"><p class="title">There are easier ways!</p><span class="aui-icon aui-icon-small aui-iconfont-warning confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>Using a Struts 2 plugin (e.g., JSON plugin, jQuery plugin, etc.) is, in general, preferred to writing the response directly from within an action. See sections following this for further details.</p></div></div><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>Struts 2 Stream result Action</b></div><div class="codeContent panelContent pdl">
<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">package actions;

import java.io.InputStream;
import java.io.StringBufferInputStream;
import com.opensymphony.xwork2.ActionSupport;

public class TextResult extends ActionSupport  {
    private InputStream inputStream;
    public InputStream getInputStream() {
        return inputStream;
    }

    public String execute() throws Exception {
        inputStream = new ByteArrayInputStream("Hello World! This is a text string response from a Struts 2 Action.".getBytes("UTF-8"));
        return SUCCESS;
    }
}
</pre>
</div></div><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>Struts 2 Configuring the TextResult Action</b></div><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">&lt;action name="text-result" class="actions.TextResult"&gt;
    &lt;result type="stream"&gt;
        &lt;param name="contentType"&gt;text/html&lt;/param&gt;
        &lt;param name="inputName"&gt;inputStream&lt;/param&gt;
    &lt;/result&gt;
&lt;/action&gt;
</pre>
</div></div><p><img class="emoticon emoticon-tick" src="https://cwiki.apache.org/confluence/s/en_GB/5982/f2b47fb3d636c8bc9fd0b11c0ec6d0ae18646be7.1/_/images/icons/emoticons/check.png" data-emoticon-name="tick" alt="(tick)"> Struts 2 can also return a JSON (JavaScript Object Notation) response, using a <a shape="rect" class="external-link" href="http://cwiki.apache.org/S2PLUGINS/json-plugin.html">plugin</a>.</p><p>On the client side, there are two basic strategies, which can be mixed and matched.</p><p>First, you can use some type of JSP tag. Here, you don't have to know very much at all about Ajax or JavaScript. The taglib does all the work, and you just have to figure out how to use the taglib. The standard Struts 2 taglib includes several <a shape="rect" href="ajax-tags.html">Ajax JSP tags</a>, and many third-party libraries are available, including:</p><ul><li><a shape="rect" class="external-link" href="http://ajaxtags.sourceforge.net/" rel="nofollow">Ajax Tags</a></li><li><a shape="rect" class="external-link" href="http://javawebparts.sourceforge.net/" rel="nofollow">AjaxParts Taglib</a></li><li><a shape="rect" class="external-link" href="http://servletsuite.blogspot.com/2006/06/coldtags-suite-ajax-edition.html" rel="nofollow">ColdTags Suite</a></li><li><a shape="rect" class="external-link" href="http://www.jenkov.com/prizetags/introduction.tmpl" rel="nofollow">Prize Tags</a></li><li><a shape="rect" class="external-link" href="http://json-taglib.sourceforge.net/" rel="nofollow">JSON-taglib</a></li></ul><p>Alternatively, you can use a plain-old Ajax widget on a plain-old HTML page, using libraries like <a shape="rect" class="external-link" href="http://dojotoolkit.org/" rel="nofollow">Dojo</a>, <a shape="rect" class="external-link" href="http://jquery.com/" rel="nofollow">JQuery</a>, or <a shape="rect" class="external-link" href="http://developer.yahoo.com/yui/" rel="nofollow">YUI</a>, and the StreamResult or the <a shape="rect" class="external-link" href="http://cwiki.apache.org/S2PLUGINS/json-plugin.html">JSON Plugin</a>. Here, the sky's the limit, but you actually have to learn something about JavaScript as a language.</p><h2 id="AJAX-AjaxPlugins">Ajax Plugins</h2><p>While Struts works fine with Ajax out-of-the-box, for added value, several Ajax-centric plugins are available.</p><h3 id="AJAX-AjaxTagPlugins">Ajax Tag Plugins</h3><ul><li><strong>jQuery</strong>&#160;- The&#160;<a shape="rect" class="external-link" href="https://github.com/struts-community-plugins/struts2-jquery" rel="nofollow">jQuery Plugin</a>&#160;provide ajax functionality and UI Widgets an JavaScript Grid based on the jQuery javascript framework.<strong><br clear="none"></strong></li><li><strong>Ajax Parts</strong> - The <a shape="rect" class="external-link" href="http://code.google.com/p/struts2ajaxpartstaglibplugin/" rel="nofollow">AjaxParts Taglib (APT)</a> is a component of the Java Web Parts (JWP) project (<a shape="rect" class="external-link" href="http://javawebparts.sourceforge.net" rel="nofollow">http://javawebparts.sourceforge.net</a>) that allows for 100% declarative (read: no Javascript coding required!) AJAX functionality within a Java-based webapp.</li><li><strong>Dojo</strong> - The <a shape="rect" href="ajax-tags.html">Ajax Tags Dojo Plugin</a> was represented as a theme for Struts 2.0. For Struts 2.1, the Dojo tags are bundled as a plugin until version 2.3.x. Since version 2.5 this plugin is not part of th Struts2 distribution anymore&#160;</li><li><strong>YUI</strong> - The <a shape="rect" class="external-link" href="https://code.google.com/p/struts2yuiplugin/" rel="nofollow">Yahoo User Interface (YUI) Plugin</a> has only a few tags are available so far, but the YUI tags tend to be easier to use than the Dojo versions.</li></ul><h3 id="AJAX-OtherAjaxPlugins">Other Ajax Plugins</h3><ul><li><strong>Ajax File Upload</strong> - With the <a shape="rect" class="external-link" href="http://www.davidjc.com/ajaxfileupload/demo!input.action" rel="nofollow">Ajax File Upload Plugin</a> we can upload a file to the server and asynchronously monitor its progress.</li><li><strong>GWT</strong> - The <a shape="rect" class="external-link" href="https://code.google.com/p/struts2gwtplugin/" rel="nofollow">Google Web Toolkit Plugin</a> exposes Struts 2 actions to the GWT RPC mechanism.</li><li><strong>JSON</strong> - The <a shape="rect" href="json-plugin.html">JSON Plugin</a> serializes Actions properties into JSON, making it easy to respond to JavaScript requests.</li></ul><p>See the <a shape="rect" class="external-link" href="http://cwiki.apache.org/S2PLUGINS/home.html">Struts Plugin Repository</a> for a complete list of Struts 2 plugins.</p><h2 id="AJAX-AjaxResultswithJSP">Ajax Results with JSP</h2><p>While server pages are most often used to generate HTML, we can use server pages to create other types of data streams. Here's an example:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>book.jsp</b></div><div class="codeContent panelContent pdl">
<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">&lt;%@ page import="java.util.Iterator,
		 java.util.List,
		 com.esolaria.dojoex.Book,
		 com.esolaria.dojoex.BookManager" %&gt;
&lt;%
	String bookIdStr = request.getParameter("bookId");
	int bookId = (bookIdStr == null || "".equals(bookIdStr.trim())) 
		? 0 : Integer.parseInt(bookIdStr);
	Book book = BookManager.getBook(bookId);
	if (book != null) {
		out.println(book.toJSONString());
		System.out.println("itis: " + book.toJSONString());
	}
%&gt;
</pre>
</div></div><p>In the code example, we use <code>System.out.println</code> to return a JSON data stream as the response. For more about this technique, see the article <a shape="rect" class="external-link" href="http://today.java.net/pub/a/today/2006/04/27/building-ajax-with-dojo-and-json.html" rel="nofollow">Using Dojo and JSON to Build Ajax Applications</a>.</p><h2 id="AJAX-Next:">Next: <a shape="rect" href="dependency-injection.html">Dependency Injection</a></h2></div>
        </div>

        
    </div>
</div>
<div class="footer">
    Generated by CXF SiteExporter
</div>
</body>
</html>
